#include <cstring>
#include <string>
#include <iostream>
#include <curl/curl.h>

size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp) {
    std::string *data = static_cast<std::string*>(userp);
    size_t buffer_size = size * nmemb;

    if(data->size() > 0) {
        size_t copy_size = data->size() < buffer_size ? data->size() : buffer_size;
        std::memcpy(ptr, data->c_str(), copy_size);
        data->erase(0, copy_size);
        return copy_size;
    }

    return 0;
}

void sendEmail(const std::string& smtpServer, const std::string& username, const std::string& password, const std::string& to, const std::string& subject, const std::string& body) {
    CURL *curl;
    CURLcode res;
    struct curl_slist *recipients = NULL;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, smtpServer.c_str());
        curl_easy_setopt(curl, CURLOPT_USERNAME, username.c_str());
        curl_easy_setopt(curl, CURLOPT_PASSWORD, password.c_str());

        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, username.c_str());

        recipients = curl_slist_append(recipients, to.c_str());
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

        std::string emailData = "To: " + to + "\r\n" +
                                "From: " + username + "\r\n" +
                                "Subject: " + subject + "\r\n" +
                                "\r\n" +
                                body + "\r\n";

        curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
        curl_easy_setopt(curl, CURLOPT_READDATA, &emailData);
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

        // 启用 SSL/TLS
        curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);

        // 启用调试信息
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        res = curl_easy_perform(curl);

        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

        curl_slist_free_all(recipients);
        curl_easy_cleanup(curl);
    }
}

int main() {
    std::string smtpServer = "smtps://smtp.titan.email:465"; // SMTP服务器和端口
    std::string username = "riki.zhang@amutec.cn"; // 替换为你的SMTP用户名
    std::string password = "$Zh4&R!k^3170"; // 替换为你的SMTP密码
    std::string to = "riki.zhang@amutec.cn";
    std::string subject = "Test Email";
    std::string body = "This is a test email.";

    sendEmail(smtpServer, username, password, to, subject, body);

    return 0;
}
